using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Web.Routing;

namespace WebApp.Extensions
{
    public static class MvcHelperExtensions
    {
        public static string GetControllerName(this Type controllerType)
        {
            return controllerType.Name.Replace("Controller", string.Empty);
        }

        public static string GetActionName(this LambdaExpression actionExpression)
        {
            return ((MethodCallExpression) actionExpression.Body).Method.Name;
        }

        public static string GetAreaName(this Type type)
        {
            Debug.Assert(type.Namespace != null, string.Format("type {0} is not defined in any Namespace", type.Name));

            var namespaces = type.Namespace.ToLowerInvariant().Split('.');
            var areaIndex = GetAreaIndex(namespaces);
            return areaIndex < 0 ? null : namespaces[areaIndex + 1];
        }

        private static int GetAreaIndex(IList<string> namespaces)
        {
            for (var i = 0; i < namespaces.Count; i++)
            {
                if (namespaces[i] == "areas")
                {
                    return i;
                }
            }

            return -1;
        }

        public static void ProcessArea(this RouteValueDictionary routeValues, Type targetControllerType)
        {
            var areaName = targetControllerType.GetAreaName() ?? string.Empty;

            if (routeValues.ContainsKey("area"))
                routeValues["area"] = areaName;
            else
                routeValues.Add("area", areaName);
        }
	
    }
}